package io.github.wanggit.antrpc.log.analyzer.config;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

@Configuration
public class ElasticsearchConfiguration {

  @Value("${elasticsearch.uris}")
  private String uris;

  @Value("${elasticsearch.username}")
  private String userName;

  @Value("${elasticsearch.password}")
  private String password;

  @Bean(name = "highLevelClient")
  public RestHighLevelClient highLevelClient() {
    RestClientBuilder restClientBuilder = RestClient.builder(makeHttpHost(uris));
    if (StringUtils.hasText(userName) && StringUtils.hasText(password)) {
      CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
      credentialsProvider.setCredentials(
          AuthScope.ANY, new UsernamePasswordCredentials(userName, password));
      restClientBuilder.setHttpClientConfigCallback(
          httpAsyncClientBuilder -> {
            httpAsyncClientBuilder.disableAuthCaching();
            return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
          });
    }
    return new RestHighLevelClient(restClientBuilder);
  }

  private HttpHost[] makeHttpHost(String uris) {
    if (null == uris) {
      throw new IllegalArgumentException();
    }
    String[] tmps = uris.split(",");
    HttpHost[] posts = new HttpHost[tmps.length];
    for (int i = 0; i < tmps.length; i++) {
      String[] address = tmps[i].trim().split(":");
      String ip = address[0];
      int port = Integer.parseInt(address[1]);
      posts[i] = new HttpHost(ip, port, "http");
    }
    return posts;
  }
}
